﻿using MapleLeaf.Core;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace DiLe.Mes.Cloud.Components {
    /// <summary>
    /// 
    /// </summary>
    public static class AuthComponent {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        public static void AddAuthComponent(this WebApplicationBuilder builder) {

            var jwtModel = AppHelper.GetJwtSetting();

            builder.Services.AddAuthentication(x => {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x => {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtModel.IssuerSigningKey!)),//JWT秘钥
                    ValidIssuer = jwtModel.ValidIssuer,//发行者,
                    ValidAudience = jwtModel.ValidAudience,//接收者,
                    ValidateIssuer = jwtModel.ValidateIssuer,
                    ValidateAudience = jwtModel.ValidateAudience,
                    // 是否验证Token有效期，使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true,
                    //注意这是缓冲过期时间，总的有效时间等于这个时间加上jwt的过期时间，如果不配置，默认是5m
                    ClockSkew = TimeSpan.FromSeconds(jwtModel.ClockSkew)
                };
            });
        }
    }
}
